<template>
  <el-tabs
    v-model="tabsValue"
    type="card"
    :closable="isClosable"
    @tab-remove="removeTab"
    @tab-change="tabChange"
  >
    <el-tab-pane v-for="item in tabList" :key="item.path" :label="item.menuName" :name="item.path">
    </el-tab-pane>
  </el-tabs>
</template>
<script lang="ts" setup>
import { useCommonStore } from '@/stores/common'
import { goPage } from '@/utils/commonFn'
import type { TabPaneName } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import router from '@/router'
const tabsValue = ref()
const tabList = ref<commonTypes.menuItem[]>([])
const isClosable = ref(true)
onMounted(() => {
  tabList.value = JSON.parse(sessionStorage.getItem('breadcrumbsList') as string)
  useCommonStore().setBreadcrumbsList(tabList.value)
  if (sessionStorage.getItem('currentRoute')) {
    tabsValue.value = JSON.parse(sessionStorage.getItem('currentRoute') as string).path
    goPage({
      path: tabsValue.value as string,
      isNoBread: true
    })
  }
})
watch(
  () => useCommonStore().breadcrumbsList,
  (info) => {
    // 面包屑长度为1时不能删除页面
    if (info.length === 1) {
      isClosable.value = false
    } else {
      isClosable.value = true
    }
    tabList.value = info
  },
  { immediate: true, deep: true }
)
watch(
  () => useCommonStore().currentRoute,
  (info) => {
    tabsValue.value = info?.path
    goPage({ path: info?.path as string, isNoBread: true })
  }
)
const tabChange = (info: TabPaneName) => {
  const item = tabList.value.filter((item) => item.path === info)[0]
  if (item) {
    useCommonStore().setCurrentRoute(item)
    goPage({ path: info as string, isNoBread: true })
  }
}
watch(
  () => router.currentRoute.value,
  (toPath) => {
    if (toPath.path != '/') {
      tabChange(toPath.fullPath)
    }
  },
  { immediate: true, deep: true }
)
const removeTab = (targetName: TabPaneName) => {
  const tabs = tabList.value
  let activeName = tabsValue.value
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.path === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.path
        }
      }
    })
  }
  tabsValue.value = activeName
  tabChange(activeName)
  tabList.value = tabs.filter((tab) => tab.path !== targetName)
  useCommonStore().setBreadcrumbsList(tabList.value)
}
</script>
<style></style>
